package edu.hawaii.ics314.ical.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;

import edu.hawaii.ics314.ical.model.Calendar;
import edu.hawaii.ics314.ical.model.Calendars;
import edu.hawaii.ics314.ical.model.CalendarComponent.ComponentPriority;
import edu.hawaii.ics314.ical.view.ViewEvent;
import edu.hawaii.ics314.ical.view.ViewListener;

public class CheckInTwoViewController implements ViewListener<String> {

	@Override
	public void onViewResult(ViewEvent<String> evt) {
		// Isolate individual file names and remove whitespace.
		String[] fileNames = evt.getResult().split(",");
		for(int i = 0; i < fileNames.length; i++) {
			fileNames[i] = fileNames[i].trim();
		}
		// Deserialize into Calendar objects.
		for(int i = 0; i < fileNames.length; i++) {
			try {
				File inputCalFile = new File(fileNames[i]).getAbsoluteFile();
				Calendar inputCal = Calendar.fromFile(inputCalFile);
				Calendar freeTime = Calendars.freeTime(inputCal, ComponentPriority.UNDEFINED);
				File outputCalFile = new File(inputCalFile.getParentFile(), "Free Time - " + inputCalFile.getName());
				if(!outputCalFile.getParentFile().exists()) {
					outputCalFile.getParentFile().mkdirs();
				}
				if(!outputCalFile.exists()) {
					outputCalFile.createNewFile();
				}
				freeTime.toFile(outputCalFile);
				System.out.println("Wrote .ics file: " + outputCalFile.getAbsolutePath());
			} catch (IOException | ParseException e) {
				System.out.printf("An error occurred while reading file '%s': %s%n%nError Detail:%n", 
						fileNames[i], e.getMessage());
				e.printStackTrace(System.out);
			}
		}
	}

}
